package misc

import scala.util.Success


/**
  * Created by shichen on 2017/5/3.
  *
  */

class Creature {
  val range:Int = 10
  val env:Array[Int] = new Array[Int](range)
}

class Ant extends Creature {
  override val range: Int = 2
  //Ant的env大小会被初使化为0
}

object Test {
  def main(args: Array[String]): Unit = {
    sortTest()

    val f = "3.14s"
    val r1 = scala.util.Try(f.toDouble)
    val res = r1 match {
      case Success(d) => d
      case _ => "failed"
    }
    println(res)


    //t_variable_parameter()
    //t_array()
    //val b = new BasicStructure; b.t_map()

    //t_high_scale_func()
    //t_pattern_match()
    //t_trait()
  }

  def sortTest(): Unit = {
    val s = List("a","d","F","B","e")
    val n = List(3,7,2,1,5)
    val m = Map(-2 -> 5,
      2 -> 6,
      5 -> 9,
      1 -> 2,
      0 -> -16,
      -1 -> -4)
    println(s.sorted , n.sorted)

    def comfn1(e1: String, e2: String) = (e1 compareToIgnoreCase e2) < 0
    def comfn2(e1: String, e2: String) = (e1.toLowerCase() < e2.toLowerCase())

    println(s.sortWith(comfn1))
    println(s.sortWith(comfn2))

    m.toList.sorted foreach {
      case (key,value) =>
        println("sorted by key:" + key + "=" + value)
    }
    m.toList.sortBy(_._2) foreach{
      case (key,value) =>
        println("sorted by value:" + key + "=" + value)
    }
  }

  //def changePara(x: Int) = { x = 1 }

  def printAny(x:Any): Unit = {
    println(x)
  }
  def printUnit(x: Unit): Unit = {
    println(x)
  }

  ///////////////////////////////////////////
  //变长参数
  def t_variable_parameter(): Unit = {
    val s = sum(1,2,3,4,5)
    println(s)
    //val s2 = sum(1 to 5)// 如果传入的是单个参数，应该是个整数，而不是整数区间
    //若要当作整数区间，可通过:_*来转化成参数序列
    val s2 = sum(1 to 5 :_*)
    println(s2)
    println(recursiveSum(1,3,5,7,9))
  }
  def recursiveSum(args: Int*):Int = {
    if (args.length == 0) 0
    else args.head + recursiveSum(args.tail :_*)
  }
  def sum(args: Int*) = {
    var res = 0
    for (arg <- args) res += arg
    res
  }

}
